/**
 * Find is like get, but provides a query into the wifi info cache of the device
 * specified
 */
package sxe.core.wifi;

import snobject.snLong;
import snobject.snNil;
import snobject.snObject;
import snobject.snObjectArgList;
import snobject.snSensor;
import snobject.snStruct;
import step.EvaluationFailure;
import step.FunctionWrapper;
import sxe.sensors.GenericSensor;
import sxe.sensors.KismetSensor;
import sxe.sensors.SensorDetector;

public class find extends FunctionWrapper {

	private long delayMax = -1;
	private long delayMin = -1;
	private long delayAvg = -1;
	private long delayCt = -1;
	
	@Override
	public snObject Call(snObjectArgList argv) throws EvaluationFailure,
			ClassCastException, ArrayIndexOutOfBoundsException {
		
		snSensor sens = argv.popSensor();

		String sSensorID = sens.getSensorID();
		String sSensorType = sens.getSensorType();
		String macAddr = argv.popString().getString();
		
		if(sSensorType == null)
			sSensorType = GenericSensor.TYPE_KISMET;
		
		GenericSensor sensor = SensorDetector.GetDevice( sSensorID, sSensorType);
						
		if( sensor == null ) {
			System.err.println("Could not locate a sensor with ID '" + sSensorID + "' of type " + sSensorType );
			throw new EvaluationFailure(this.expnode,"Couldn't get sensor " + sSensorID);
		}
		if(!(sensor instanceof KismetSensor)){
			System.err.println("Sensor requested for wifi.get (" + sSensorID + ")is not of wifi-sensor type, rather its " + sSensorType );
			throw new EvaluationFailure(this.expnode,"Sensor requested for wifi.get (" + sSensorID + ")is not of wifi-sensor type, rather its " + sSensorType );			
		}

		KismetSensor kSensor = (KismetSensor) sensor;

		if(!kSensor.isAlive()){
			throw new EvaluationFailure( this.expnode,
					 "Wireless sensor with ID: " +
					 sSensorID + " is not available/active on this SXE host.");
		}
				

		snObject sO = kSensor.getData(macAddr);
		if(sO.equals(snNil.NIL))
			return sO;
		snStruct t = (snStruct)sO; 
		
		//long lNow = System.nanoTime();
		long lNow = System.currentTimeMillis();
		long lThen = ((snLong)t.get("MSG_TIME")).getLong();
		/*
		long lDelay = (lNow - lThen);
		if(delayMax==-1){
			delayMax = lDelay;
			delayMin = lDelay;
			delayAvg = lDelay;
			delayCt = 1;
		}
		else{
			delayMax = (lDelay > delayMax)? lDelay : delayMax;
			delayMin = (lDelay < delayMin)? lDelay : delayMin;
			delayCt++;
			delayAvg = ((delayCt-1)*delayAvg + lDelay)/delayCt;
		}
		
		System.err.println("[Cur delay ==" + lDelay + "ms]\n" +
						   "[Avg delay ==" + delayAvg + "ms]\n" +					
						   "[Min delay ==" + delayMin + "ms]\n" +				   
						   "[Max delay ==" + delayMax + "ms]\n" +						   
						   "[Delay ct  ==" + delayCt + "]\n" );
		*/
		t.put("MSG_PULL_DELAY", String.valueOf(lNow-lThen));
		
		return t;
	}

}
